'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken')

class ArticleController extends Controller {
    async publish() { //发布修改文章接口
        const publishResult = {
            author: {
                type: 'string',
                required: true
            }
        }
        let body = this.ctx.request.body;
        let tokenContent = await jwt.verify(this.ctx.header.authorization, this.config.jwt.jwtKey); //如果 token 过期或验证失败，将返回401
        try {
            this.ctx.validate(publishResult, body);
            this.ctx.service.mysql.insert('article',{
                title: body.title,
                subtitle: body.subtitle,
                type: body.type,
                author: body.author,
                headImg: body.headImg,
                content: body.content,
                creatTime: new Date().getTime(),
                publishTime: new Date().getTime(),
                status: body.status,
                adminId: tokenContent.id
            })
            this.ctx.helper.resultData(0, '', '发布成功')
        } catch (err) {
            this.ctx.helper.resultData(-1,'',err)
        }
    }
    async articleList(){
        let body = this.ctx.request.body;
        try {
            let result = await this.ctx.service.mysql.findAll('article',{
                /* where:{
                    title: body.title || '',
                    type: body.type || '',
                    author: body.author || '',
                    status: body.status || ''
                }, */
                limit: 10,
                offset: 10 * (body.page-1)
            })
            this.ctx.helper.resultData(0, {
                items: result,
                total: 40
            }, 'success')
        } catch (error) {
            this.ctx.helper.resultData(-1,'',error)
        }
    }
}

module.exports = ArticleController;